<?php

namespace app\api\controller;

use app\common\service\Order as OrderService;
use app\common\service\WxNotify;


class Order extends ApiBase {

    public function index() {
        $this->checkUserToken();
        $condition['user_id'] = $this->user_id;
        $result               = model('Order')->getOrderList($condition);
        return show(0, '获取订单成功', $result);
    }

    public function read($id) {
        $query = input('get.');
        $this->checkUserToken();
        if ($query['type'] == 'detail') {
            $result = model('Order')->getOrderDetail($id);
            return show(config('code.success'), '获取订单详情成功', $result);
        }
        if ($query['type'] == 'pay') {
            $order = model('Order')->get($id);
            if ($order->status == config('code.unpaid')) {
                $orderService   = new OrderService($order->id, $this->openid);
                $wxPrepayResult = $orderService->getWxPrepay($order);
                return show(config('code.success'), '创建订单成功', $wxPrepayResult);
            } else {
                return show(config('code.fail'), '该订单已付款');
            }
        }
    }

    public function save() {
        validate('Order')->goCheck();
        $data             = input('post.');
        $data['order_no'] = OrderService::makeOrderNo();
        $data['user_id']  = $this->user_id;
        $data['status']   = config('code.unpaid');
        $data['products'] = json_encode($data['products']);
        $order_id         = model('Order')->add($data);
        $orderService     = new OrderService($order_id, $this->openid);
        $wxPrepayResult   = $orderService->getWxPrepay($data);
        return show(0, '创建订单成功', $wxPrepayResult);
    }

    public function update($id) {
        $param = input('param.');
        $order = model('Order')->get($id);
        if ($order->status == config('code.paid')) {
            $orderService   = new OrderService($order->id, $this->openid);
            $wxPrepayResult = $orderService->getWxPrepay($order);
            return show(config('code.success'), '创建订单成功', $wxPrepayResult);
        } else {
            return show(config('code.fail'), '该订单已付款');
        }
    }

    public function delete($id) {
        $result = model('Order')
            ->where(['id' => $id])
            ->update(['status' => config('code.status_delete')]);
        if (!$result) {
            return show(config('code.fail'), '删除订单失败');
        }
        return show(config('code.success'), '删除订单成功');
    }

    public function wxNotice() {
        $notice = new WxNotify();
        $notice->Handle();
    }
}